<template>
  <section id="comments" class="p-24" :style="{
    backgroundColor: bgColor
  }">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div class="max-w-4xl mx-auto">
        <!-- 标题区域 -->
        <div class="text-center mb-12" v-if="showHeader">
          <h2 class="text-[clamp(1.75rem,4vw,2.5rem)] font-bold mt-2 mb-4 text-gray-800">用户评论</h2>
          <p class="text-lg text-gray-600 leading-relaxed">查看其他用户的使用体验和反馈</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="isLoading" class="flex flex-col items-center justify-center py-16 bg-white rounded-xl shadow-sm">
          <div class="w-12 h-12 border-4 border-gray-200 border-t-primary rounded-full animate-spin mb-4"
            :style="{ borderTopColor: primaryColor }"></div>
          <p class="text-gray-600">正在加载评论数据...</p>
        </div>

        <!-- 评论列表 -->
        <div v-else class="space-y-6 mb-12">
          <div v-for="(comment, index) in displayedComments" :key="index"
            class="bg-white p-6 rounded-xl shadow-sm transition-all duration-300 hover:shadow-md"
            :style="{ borderRadius: `${cardRadius}px` }">
            <div class="flex items-start mb-4">
              <img :src="comment.avatarUrl" :alt="comment.author + '的头像'"
                class="w-12 h-12 rounded-full object-cover mr-4">
              <div>
                <div class="flex items-center">
                  <h4 class="font-bold mr-2">{{ comment.author }}</h4>
                  <div class="flex text-yellow-400 text-sm">
                    <i v-for="(star, sIndex) in 5" :key="sIndex" class="fa" :class="{
                      'fa-star': star <= comment.rating,
                      'fa-star-half-o': star === comment.rating + 0.5,
                      'fa-star-o': star > comment.rating
                    }"></i>
                  </div>
                </div>
                <p class="text-gray-600 text-sm">{{ formatDate(comment.date) }}</p>
              </div>
            </div>
            <p class="text-gray-800 mb-4" v-html="comment.content"></p>
            <div class="flex items-center text-sm">
              <button class="flex items-center transition-all duration-300 mr-6"
                :class="comment.liked ? { color: primaryColor } : { color: 'rgba(31, 41, 55, 0.6)', '&:hover': { color: primaryColor } }"
                @click="toggleLike(comment, index)">
                <i class="fa fa-thumbs-up mr-1"></i>
                有用 ({{ comment.likes }})
              </button>
              <button class="flex items-center text-gray-600 transition-all duration-300 hover:text-primary"
                @click="replyToComment(index)" v-if="allowReplies">
                <i class="fa fa-reply mr-1"></i> 回复
              </button>
            </div>

            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0"
              class="mt-4 ml-16 pl-4 border-l-2 border-gray-200 space-y-4">
              <div v-for="(reply, rIndex) in comment.replies" :key="rIndex">
                <div class="flex items-start mb-2">
                  <img :src="reply.avatarUrl" :alt="reply.author + '的头像'"
                    class="w-10 h-10 rounded-full object-cover mr-3">
                  <div>
                    <div class="flex items-center">
                      <h5 class="font-bold text-sm mr-2">{{ reply.author }}</h5>
                      <span v-if="reply.isOfficial"
                        :style="{ backgroundColor: `${primaryColor}10`, color: primaryColor }"
                        class="px-2 py-0.5 text-xs rounded">
                        官方
                      </span>
                    </div>
                    <p class="text-gray-600 text-xs">{{ formatDate(reply.date) }}</p>
                  </div>
                </div>
                <p class="text-gray-800 text-sm mb-2" v-html="reply.content"></p>
              </div>
            </div>

            <!-- 回复输入框 -->
            <div v-if="comment.showReplyBox" class="mt-4 ml-16">
              <textarea v-model="comment.replyContent" rows="3"
                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary mb-3"
                placeholder="请输入回复内容"></textarea>
              <div class="flex justify-end">
                <button type="button" :style="{ backgroundColor: primaryColor }"
                  class="px-4 py-2 text-white rounded-lg hover:opacity-90 transition-all duration-300 mr-3"
                  @click="submitReply(comment, index)">
                  提交回复
                </button>
                <button type="button"
                  class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-all duration-300"
                  @click="cancelReply(comment)">
                  取消
                </button>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="displayedComments.length === 0" class="bg-white p-8 rounded-xl shadow-sm text-center"
            :style="{ borderRadius: `${cardRadius}px` }">
            <i class="fa fa-comments text-4xl text-gray-300 mb-4"></i>
            <p class="text-gray-600">暂无评论，快来发表第一条评论吧</p>
          </div>
        </div>

        <!-- 刷新按钮（仅在有数据源URL时显示） -->
        <div v-if="dataSourceUrl && !isLoading" class="flex justify-end mb-6">
          <button @click="refresh" :style="{ backgroundColor: primaryColor }"
            class="px-4 py-2 text-white rounded-lg hover:opacity-90 transition-all duration-300 flex items-center"
            :disabled="isLoading">
            <i class="fa fa-refresh mr-2"></i>
            刷新评论数据
          </button>
        </div>

        <!-- 分页 -->
        <div class="flex justify justify-center" v-if="totalPages > 1 && showPagination">
          <nav class="flex items-center space-x-1">
            <a href="#"
              class="w-10 h-10 flex items-center justify-center rounded-lg border border-gray-300 text-gray-700 hover:bg-primary hover:text-white hover:border-primary transition-all duration-300"
              @click.prevent="changePage(currentPage - 1)" :disabled="currentPage === 1">
              <i class="fa fa-angle-left"></i>
            </a>

            <!-- 页码 -->
            <template v-for="page in visiblePages" :key="page">
              <span v-if="page === '...'" class="w-10 h-10 flex items-center justify-center text-gray-500">
                ...
              </span>
              <a v-else href="#"
                class="w-10 h-10 flex items-center justify-center rounded-lg transition-all duration-300" :class="{
                  'bg-primary text-white': page === currentPage,
                  'border border-gray-300 text-gray-700 hover:bg-primary hover:text-white hover:border-primary': page !== currentPage
                }" @click.prevent="changePage(page)">
                {{ page }}
              </a>
            </template>

            <a href="#"
              class="w-10 h-10 flex items-center justify-center rounded-lg border border-gray-300 text-gray-700 hover:bg-primary hover:text-white hover:border-primary transition-all duration-300"
              @click.prevent="changePage(currentPage + 1)" :disabled="currentPage === totalPages">
              <i class="fa fa-angle-right"></i>
            </a>
          </nav>
        </div>

        <!-- 发表评论 -->
        <div class="mt-12 bg-white p-6 rounded-xl shadow-sm" :style="{ borderRadius: `${cardRadius}px` }"
          v-if="showCommentForm">
          <h3 class="text-xl font-bold mb-4">发表评论</h3>
          <form @submit.prevent="handleCommentSubmit">
            <div class="mb-4">
              <label class="block text-gray-800 mb-2">您的评分</label>
              <div class="flex text-gray-300 text-xl">
                <i v-for="(star, index) in 5" :key="index" class="fa fa-star cursor-pointer transition-all duration-300"
                  :class="{ 'text-yellow-400': index < newCommentRating }" @click="setRating(index + 1)"
                  @mouseover="setHoverRating(index + 1)" @mouseleave="resetHoverRating"></i>
              </div>
            </div>

            <div class="mb-6">
              <label for="comment-content" class="block text-gray-800 mb-2">评论内容</label>
              <textarea id="comment-content" rows="4"
                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"
                placeholder="请分享您的使用体验和建议" v-model="newCommentContent" :required="commentFormRequired"></textarea>
            </div>

            <button type="submit"
              class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all duration-300"
              :disabled="isSubmittingComment">
              <span v-if="!isSubmittingComment">提交评论</span>
              <span v-if="isSubmittingComment">
                <i class="fa fa-spinner fa-spin mr-2"></i>提交中...
              </span>
            </button>
          </form>

          <!-- 评论提交结果 -->
          <div v-if="commentSubmitStatus" class="mt-4 p-3 rounded-lg text-sm" :class="{
            'bg-green-50 text-green-700': commentSubmitStatus === 'success',
            'bg-red-50 text-red-700': commentSubmitStatus === 'error'
          }">
            <p v-if="commentSubmitStatus === 'success'">
              <i class="fa fa-check-circle mr-1"></i>评论提交成功
            </p>
            <p v-if="commentSubmitStatus === 'error'">
              <i class="fa fa-exclamation-circle mr-1"></i>评论提交失败，请稍后再试
            </p>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'CommentSection',
  // 低代码平台元数据
  lowcode: {
    meta: {
      name: 'comment-section',
      displayName: '评论模块',
      description: '用于展示用户评论和允许用户发表评论的组件',
      icon: 'fa-star',
      category: '交互组件',
      version: '1.0.0',
      isContainer: false
    },

    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'bgColor',
            label: '背景色',
            type: 'color',
            defaultValue: '#f9fafb'
          },
          {
            name: 'showHeader',
            label: '显示标题区域',
            type: 'boolean',
            defaultValue: true
          }
        ]
      },
      {        title: '数据源配置',        fields: [          {            name: 'dataSourceUrl',            label: '数据源URL',            type: 'text',            description: 'API接口地址，用于动态加载评论数据',            defaultValue: ''          },          {            name: 'autoLoad',            label: '自动加载',            type: 'boolean',            defaultValue: true          }        ]      },
      {
        title: '布局配置',
        fields: [
          {
            name: 'cardRadius',
            label: '卡片圆角',
            type: 'number',
            min: 0,
            max: 20,
            defaultValue: 8
          },
          {
            name: 'commentsPerPage',
            label: '每页评论数',
            type: 'number',
            min: 1,
            max: 20,
            defaultValue: 5
          },
          {
            name: 'showPagination',
            label: '显示分页',
            type: 'boolean',
            defaultValue: true
          }
        ]
      },
      {
        title: '功能配置',
        fields: [
          {
            name: 'showCommentForm',
            label: '显示评论表单',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'allowReplies',
            label: '允许回复评论',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'commentFormRequired',
            label: '评论内容必填',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'defaultComments',
            label: '默认评论数据',
            type: 'array',
            description: '初始显示的评论数据',
            defaultValue: []
          }
        ]
      }
    ],

    events: [
      {
        name: 'commentSubmit',
        label: '评论提交',
        description: '用户提交评论时触发',
        parameters: [
          { name: 'comment', type: 'object', description: '评论数据' }
        ]
      },
      {
        name: 'replySubmit',
        label: '回复提交',
        description: '用户提交回复时触发',
        parameters: [
          { name: 'reply', type: 'object', description: '回复数据' },
          { name: 'commentIndex', type: 'number', description: '被回复的评论索引' }
        ]
      },
      {
        name: 'likeToggle',
        label: '点赞状态切换',
        description: '用户点赞或取消点赞时触发',
        parameters: [
          { name: 'comment', type: 'object', description: '评论数据' },
          { name: 'liked', type: 'boolean', description: '是否点赞' }
        ]
      },
      {
        name: 'pageChange',
        label: '页码切换',
        description: '用户切换评论页码时触发',
        parameters: [
          { name: 'page', type: 'number', description: '当前页码' }
        ]
      },
      {
        name: 'dataLoaded',
        label: '数据加载完成',
        description: '从外部数据源加载评论数据完成时触发',
        parameters: [
          { name: 'comments', type: 'array', description: '加载的评论数据' }
        ]
      },
      {
        name: 'dataLoadError',
        label: '数据加载失败',
        description: '从外部数据源加载评论数据失败时触发',
        parameters: [
          { name: 'error', type: 'object', description: '错误信息' }
        ]
      }
    ],

    actions: [
      {
        name: 'addComment',
        label: '添加评论',
        description: '手动添加一条评论',
        parameters: [
          { name: 'comment', type: 'object', required: true, description: '要添加的评论数据' }
        ]
      },
      {
        name: 'clearComments',
        label: '清空评论',
        description: '清除所有评论'
      },
      {
        name: 'setPage',
        label: '设置页码',
        description: '跳转到指定页码',
        parameters: [
          { name: 'page', type: 'number', required: true, description: '目标页码' }
        ]
      }
    ]
  },

  props: {
    // 颜色配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    bgColor: {
      type: String,
      default: '#f9fafb'
    },

    children: {
      type: Array,
      default: () => []
    },

    // 数据源配置
    dataSourceUrl: {
      type: String,
      default: ''
    },
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 布局配置
    cardRadius: {
      type: Number,
      default: 8,
      validator: (value) => value >= 0 && value <= 20
    },
    commentsPerPage: {
      type: Number,
      default: 5,
      validator: (value) => value >= 1 && value <= 20
    },
    showPagination: {
      type: Boolean,
      default: true
    },

    // 功能配置
    showHeader: {
      type: Boolean,
      default: true
    },
    showCommentForm: {
      type: Boolean,
      default: true
    },
    allowReplies: {
      type: Boolean,
      default: true
    },
    commentFormRequired: {
      type: Boolean,
      default: true
    },
    defaultComments: {
      type: Array,
      default: () => [
        {
          author: '李先生',
          avatarUrl: 'https://picsum.photos/seed/user1/100/100',
          rating: 5,
          date: '2023-10-15',
          content: '系统非常好用，极大地提高了我们公司的工作效率。客服响应也很及时，有问题都能很快解决。推荐给需要数字化转型的企业！',
          likes: 24,
          liked: false,
          replies: []
        },
        {
          author: '张女士',
          avatarUrl: 'https://picsum.photos/seed/user2/100/100',
          rating: 4.5,
          date: '2023-09-28',
          content: '功能很全面，基本满足了我们的需求。实施过程比预期的要顺利，顾问团队很专业。唯一的小缺点是部分报表功能可以再优化一下。',
          likes: 18,
          liked: false,
          replies: [
            {
              author: '智联科技客服',
              avatarUrl: 'https://picsum.photos/seed/admin/100/100',
              date: '2023-09-29',
              content: '感谢您的反馈！我们已经记录了您关于报表功能的建议，将在下次更新中进行优化。如有其他问题，欢迎随时联系我们。',
              isOfficial: true
            }
          ]
        },
        {
          author: '王先生',
          avatarUrl: 'https://picsum.photos/seed/user3/100/100',
          rating: 4,
          date: '2023-09-10',
          content: '系统整体不错，性价比很高。初期员工培训需要一点时间，但上手后操作还是很简单的。希望能多提供一些行业解决方案的案例参考。',
          likes: 12,
          liked: false,
          replies: []
        }
      ]
    }
  },

  data() {
    return {
      // 评论数据
      comments: [...this.defaultComments],

      // 分页状态
      currentPage: 1,

      // 新评论表单
      newCommentRating: 0,
      hoverRating: 0,
      newCommentContent: '',
      isSubmittingComment: false,
      commentSubmitStatus: null,

      // 临时存储所有评论的原始数据
      allComments: [...this.defaultComments],

      // 加载状态
      isLoading: false,

      // 原始数据备份（用于数据源切换时恢复）
      originalComments: [...this.defaultComments]
    };
  },

  mounted() {
    // 保存原始数据，用于恢复
    this.originalComments = JSON.parse(JSON.stringify(this.defaultComments));

    // 自动加载数据
    if (this.autoLoad && this.dataSourceUrl) {
      this.loadDataFromSource();
    }
  },

  computed: {
    // 总页数
    totalPages() {
      return Math.ceil(this.comments.length / this.commentsPerPage);
    },

    // 当前页显示的评论
    displayedComments() {
      const startIndex = (this.currentPage - 1) * this.commentsPerPage;
      return this.comments.slice(startIndex, startIndex + this.commentsPerPage);
    },

    // 可见页码（处理大量页码时显示省略号）
    visiblePages() {
      const pages = [];
      const total = this.totalPages;
      const current = this.currentPage;

      // 总是显示第一页
      pages.push(1);

      // 当总页数大于5时，处理中间省略
      if (total > 5) {
        // 当前页在前面部分
        if (current <= 3) {
          pages.push(2, 3, 4, '...', total);
        }
        // 当前页在中间部分
        else if (current > 3 && current < total - 2) {
          pages.push('...', current - 1, current, current + 1, '...', total);
        }
        // 当前页在后面部分
        else {
          pages.push('...', total - 3, total - 2, total - 1, total);
        }
      }
      // 总页数小于等于5时，显示所有页码
      else {
        for (let i = 2; i <= total; i++) {
          pages.push(i);
        }
      }

      return pages;
    }
  },

  watch: {
    // 当默认评论数据变化时更新
    defaultComments: {
      handler(newVal) {
        this.comments = [...newVal];
        this.allComments = [...newVal];
        this.currentPage = 1;
        this.originalComments = JSON.parse(JSON.stringify(newVal));
      },
      deep: true
    },

    // 当数据源URL变化时，重新加载数据
    dataSourceUrl(newUrl, oldUrl) {
      if (this.autoLoad && newUrl && newUrl !== oldUrl) {
        this.loadDataFromSource();
      }
    }
  },

  methods: {
    /**
     * 从数据源加载数据
     */
    async loadDataFromSource() {
      if (!this.dataSourceUrl) {
        this.$emit('dataLoadError', { message: '数据源URL不能为空' });
        return;
      }

      this.isLoading = true;

      try {
        const response = await fetch(this.dataSourceUrl, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        // 验证数据格式
        if (!Array.isArray(data)) {
          throw new Error('数据格式错误：返回的不是数组');
        }

        // 处理返回的数据
        this.comments = JSON.parse(JSON.stringify(data));
        this.allComments = JSON.parse(JSON.stringify(data));
        this.currentPage = 1;

        this.$emit('dataLoaded', data);
      } catch (error) {
        console.error('加载评论数据失败:', error);
        this.$emit('dataLoadError', error);
      } finally {
        this.isLoading = false;
      }
    },

    /**
     * 刷新数据
     */
    refresh() {
      if (this.dataSourceUrl) {
        this.loadDataFromSource();
      }
    },

    /**
     * 恢复原始数据
     */
    restoreOriginalData() {
      this.comments = JSON.parse(JSON.stringify(this.originalComments));
      this.allComments = JSON.parse(JSON.stringify(this.originalComments));
      this.currentPage = 1;
    },

    /**
    /**
     * 格式化日期
     */
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
    },

    /**
     * 切换点赞状态
     */
    toggleLike(comment, index) {
      if (comment.liked) {
        comment.liked = false;
        comment.likes--;
      } else {
        comment.liked = true;
        comment.likes++;
      }
      this.$emit('likeToggle', comment, comment.liked);
    },

    /**
     * 回复评论
     */
    replyToComment(index) {
      // 关闭其他评论的回复框
      this.comments.forEach((c, i) => {
        if (i !== index) {
          c.showReplyBox = false;
        }
      });

      // 切换当前评论的回复框显示状态
      this.comments[index].showReplyBox = !this.comments[index].showReplyBox;
      // 初始化回复内容
      if (!this.comments[index].replyContent) {
        this.comments[index].replyContent = '';
      }
    },

    /**
     * 取消回复
     */
    cancelReply(comment) {
      comment.showReplyBox = false;
    },

    /**
     * 提交回复
     */
    submitReply(comment, commentIndex) {
      if (!comment.replyContent.trim()) return;

      // 创建回复对象
      const newReply = {
        author: '访客', // 在实际应用中可以替换为当前登录用户
        avatarUrl: 'https://picsum.photos/seed/visitor/100/100',
        date: new Date().toISOString().split('T')[0],
        content: comment.replyContent,
        isOfficial: false
      };

      // 添加回复到评论
      if (!comment.replies) {
        comment.replies = [];
      }
      comment.replies.push(newReply);

      // 清空回复内容并关闭回复框
      comment.replyContent = '';
      comment.showReplyBox = false;

      // 触发回复提交事件
      this.$emit('replySubmit', newReply, commentIndex);
    },

    /**
     * 切换页码
     */
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;

      this.currentPage = page;
      this.$emit('pageChange', page);

      // 滚动到评论区域顶部
      document.getElementById('comments').scrollIntoView({ behavior: 'smooth' });
    },

    /**
     * 设置评分
     */
    setRating(rating) {
      this.newCommentRating = rating;
    },

    /**
     * 设置悬停评分
     */
    setHoverRating(rating) {
      if (this.newCommentRating === 0) {
        this.hoverRating = rating;
      }
    },

    /**
     * 重置悬停评分
     */
    resetHoverRating() {
      this.hoverRating = 0;
    },

    /**
     * 处理评论提交
     */
    handleCommentSubmit() {
      if (!this.newCommentContent.trim() && this.commentFormRequired) return;
      if (this.newCommentRating === 0) return;

      this.isSubmittingComment = true;
      this.commentSubmitStatus = null;

      // 模拟API提交
      setTimeout(() => {
        // 创建新评论
        const newComment = {
          author: '访客', // 在实际应用中可以替换为当前登录用户
          avatarUrl: 'https://picsum.photos/seed/visitor/100/100',
          rating: this.newCommentRating,
          date: new Date().toISOString().split('T')[0],
          content: this.newCommentContent,
          likes: 0,
          liked: false,
          replies: []
        };

        // 添加到评论列表开头
        this.comments.unshift(newComment);
        this.allComments.unshift(newComment);

        // 重置表单
        this.newCommentRating = 0;
        this.newCommentContent = '';

        // 更新状态
        this.isSubmittingComment = false;
        this.commentSubmitStatus = 'success';

        // 触发评论提交事件
        this.$emit('commentSubmit', newComment);

        // 3秒后清除成功提示
        setTimeout(() => {
          this.commentSubmitStatus = null;
        }, 3000);
      }, 1000);
    },

    /**
     * 手动添加评论
     */
    addComment(comment) {
      if (typeof comment === 'object') {
        // 确保评论有必要的属性
        const newComment = {
          author: comment.author || '匿名用户',
          avatarUrl: comment.avatarUrl || 'https://picsum.photos/seed/anonymous/100/100',
          rating: comment.rating || 5,
          date: comment.date || new Date().toISOString().split('T')[0],
          content: comment.content || '',
          likes: comment.likes || 0,
          liked: comment.liked || false,
          replies: comment.replies || []
        };

        this.comments.unshift(newComment);
        this.allComments.unshift(newComment);
      }
    },

    /**
     * 清空评论
     */
    clearComments() {
      this.comments = [];
      this.allComments = [];
      this.currentPage = 1;
    },

    /**
     * 设置页码
     */
    setPage(page) {
      if (typeof page === 'number' && page > 0 && page <= this.totalPages) {
        this.currentPage = page;
        this.$emit('pageChange', page);
      }
    },

  }
}
</script>